package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.dto.OwnerDto;
import com.qf.entity.*;
import com.qf.exception.SystemException;
import com.qf.mapper.OwnerMapper;
import com.qf.result.ResponseResult;
import com.qf.service.*;
import com.qf.utils.BeanCopyUtils;
import com.qf.vo.OwnerVo;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.qf.enums.AppHttpCodeEnum.*;

/**
 * (Owner)表服务实现类
 *
 * @author makejava
 * @since 2023-02-04 22:31:26
 */
@Service("ownerService")
public class OwnerServiceImpl extends ServiceImpl<OwnerMapper, Owner> implements OwnerService {

    @Resource
    private HouseService houseService;
    @Resource
    private ElefeeService elefeeService;
    @Resource
    private PropertyService propertyService;
    @Resource
    private WaterfeeService waterfeeService;
    @Resource
    private ParkingService parkingService;

    @Override
    public ResponseResult getOwnerList(String ownerName) {
        //如果petName不为空,查询所有
        List<Owner> owners = list();
        if (!StringUtils.isEmpty(ownerName)) {
            LambdaQueryWrapper<Owner> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    .like(Owner::getOwnName, ownerName)
                    .or()
                    .like(Owner::getOwnPhone, ownerName)
                    .or()
                    .like(Owner::getCarNum, ownerName);
            owners = list(queryWrapper);
        }
        //vo拷贝
        List<OwnerVo> ownerVos = BeanCopyUtils.copyBeanList(owners, OwnerVo.class);
        ownerVos.stream()
                .map(ownerVo -> ownerVo.setHouseNum(houseService.getById(ownerVo.getHouseId()).getHouseNum()))
                .collect(Collectors.toList());

        return ResponseResult.okResult(ownerVos);
    }

    @Transactional
    @Override
    public ResponseResult addOwner(OwnerDto ownerDto) {
        Owner owner = BeanCopyUtils.copyBean(ownerDto, Owner.class);
        //查询传的房屋id是否存在
        if (Objects.isNull(houseService.getById(owner.getHouseId()))){
            return ResponseResult.errorResult(201,"未查询到该楼栋信息");
        }
        if (houseService.getById(owner.getHouseId()).getOwnId() != -1) {
            return   ResponseResult.errorResult(201,"该楼已有业主");
        }
        //查询手机号和车牌号是否存在
        LambdaQueryWrapper<Owner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Owner::getOwnPhone, owner.getOwnPhone()).or().eq(Owner::getCarNum,owner.getCarNum());
        List<Owner> ownerList = list(queryWrapper);
        if (ownerList.size() > 0) {
            return ResponseResult.errorResult(201,"车牌号或电话号已存在");
        }
        owner.setParkId(null);
        owner.setId(null);
        //新增时，更新房屋状态，添加业主
        boolean flag = save(owner);
        House house = houseService.getById(owner.getHouseId());
        house.setHouseStatus("1");
        house.setOwnId(owner.getId());
        if (!houseService.updateById(house)) {
            throw new SystemException(UPDATE_ERROR);
        }
        if (!flag) {
            throw new SystemException(INSERT_ERROR);
        }
        return ResponseResult.okResult();
    }

    @Transactional
    @Override
    public ResponseResult deleteOwner(Integer id) {
        //删除判断,业主其他数据均为空时，才允许删除·
        if (Objects.isNull(getById(id))){
            return ResponseResult.errorResult(201,"该用户不存在");
        }
        boolean billStatus = getBillStatus(getById(id).getHouseId());
        if (billStatus){
            return ResponseResult.errorResult(201,"有未删除账单");
        }
        LambdaQueryWrapper<Parking> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Parking::getOwnId,id);
        List<Parking> parkingList = parkingService.list(queryWrapper);
        if (parkingList.size() != 0){
            return ResponseResult.errorResult(201,"有未删除停车费信息");
        }
        House house = houseService.getById(getById(id).getHouseId());
        house.setHouseStatus("0");
        house.setOwnId(-1);
        System.out.println("house = " + house);
        houseService.updateById(house);
        boolean flag = removeById(id);
        if (!flag) {
            throw new SystemException(DELETE_ERROR);
        }
        return ResponseResult.okResult();
    }

    @Transactional
    @Override
    public ResponseResult updateOwner(OwnerDto ownerDto) {

        Owner owner = BeanCopyUtils.copyBean(ownerDto, Owner.class);
        if (Objects.isNull(getById(owner.getId()))){
            return ResponseResult.errorResult(201,"该用户不存在");
        }
        House oldHouse = houseService.getById(getById(owner.getId()).getHouseId());
        House newHouse = houseService.getById(owner.getHouseId());
        //查询手机号和车牌号是否存在
        LambdaQueryWrapper<Owner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Owner::getOwnPhone, owner.getOwnPhone()).or().eq(Owner::getCarNum,owner.getCarNum());
        List<Owner> ownerList = list(queryWrapper);
        if (ownerList.size() > 0) {
            return ResponseResult.errorResult(201,"车牌号或电话号已存在");
        }
        //判断更新房屋下有无未完成账单
        boolean billStatus = getBillStatus(oldHouse.getId());
        if (billStatus) {
            return ResponseResult.errorResult(201,"房屋下有未完成账单");
        }
        //如果房号改变的话，去更新房屋表，将原来房屋状态置为无业主，将更改房屋设置为有业主
        if (!oldHouse.getId().equals(newHouse.getId())) {
            newHouse.setHouseStatus(oldHouse.getHouseStatus());
            newHouse.setOwnId(oldHouse.getOwnId());
            oldHouse.setHouseStatus("0");
            oldHouse.setOwnId(-1);
            houseService.updateById(newHouse);
        }
        owner.setParkId(null);
        boolean flag = updateById(owner);
        if (!flag) {
            throw new SystemException(UPDATE_ERROR);
        }
        return ResponseResult.okResult();
    }
    //判断房屋下有无未完成账单
    public boolean getBillStatus(Integer houseId){
        LambdaQueryWrapper<Elefee> queryWrapperEle = new LambdaQueryWrapper<>();
        queryWrapperEle.eq(Elefee::getHouseId,houseId);
        List<Elefee> elefeeList = elefeeService.list(queryWrapperEle);
        if (elefeeList.size() != 0){
            return true;
        }
        LambdaQueryWrapper<Waterfee> queryWrapperWater = new LambdaQueryWrapper<>();
        queryWrapperWater.eq(Waterfee::getHouseId,houseId);
        List<Waterfee> waterfeeList = waterfeeService.list(queryWrapperWater);
        if (waterfeeList.size() != 0){
            return true;
        }
        LambdaQueryWrapper<Property> queryWrapperProperty = new LambdaQueryWrapper<>();
        queryWrapperProperty.eq(Property::getHouseId,houseId);
        List<Property> propertyList = propertyService.list(queryWrapperProperty);
        if (propertyList.size() != 0){
            return true;
        }
        return false;
    }
}
